<template>
    <table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" v-model="allChecked">
                    全选
                </th>
                <th>编号</th>
                <th>名称</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <template v-for="item in fruitsData" :key="item.id">
                <tr v-if="item.count > 0">
                    <td>
                        <input type="checkbox" :value="item.id" v-model="checkedData">
                    </td>
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.price }}</td>
                    <td>
                        <button>-</button>
                        {{ item.count }}
                        <button>+</button>
                    </td>
                    <td>{{ item.count * item.price }}</td>
                    <td><button @click="deleteItem(item)">删除</button></td>
                </tr>
            </template>
        </tbody>
    </table>
    <div>
        <a href="#" @click.prevent="deleteChecked">删除选中商品</a>
        <span>已选中{{ checkedData.length }}件商品</span>
    </div>
    <div>选中合计: {{ checkedTotalPrice }}元</div>
    <h1>{{ checkedData }}</h1>
</template>

<script setup>
import { computed, ref } from 'vue';

const fruitsData = ref([
    { id: 1, name: '苹果', count: 5, price: 4 },
    { id: 2, name: '苹果', count: 5, price: 4 },
    { id: 3, name: '苹果', count: 5, price: 4 },
])
// 选中的商品id
const checkedData = ref([]);

// 计算出【全选】的状态
const allChecked = computed({
    get() {
        return fruitsData.value.length === checkedData.value.length;
    },
    set(newValue) {
        if (newValue) {
            // 勾选了【全选】，将所有商品的id添加到checkedData中
            checkedData.value = fruitsData.value.map(item => item.id);
        } else {
            // 取消了【全选】
            checkedData.value = [];
        }
    }
})

const checkedTotalPrice = computed(() => {
    return fruitsData.value.reduce((prev, item) => {
        if (checkedData.value.includes(item.id)) {
            return item.count * item.price + prev;
        }
        return prev;
    }, 0)
})

function deleteChecked() {
    fruitsData.value = fruitsData.value.filter(item => !checkedData.value.includes(item.id))
}

</script>

<style scoped></style>